<?php
	$root = $_SERVER['DOCUMENT_ROOT'];
	include($root . "/util/session.php");//checks that the user is logged in
	include($root . "/util/privilege_check.php");
	checkPrivilege("student");
	if($_SERVER["REQUEST_METHOD"] == "POST"){
		$questions = (unserialize(base64_decode($_POST['selectedQuestions']))); # questions randomly chosen in the exam
		#echo $_SESSION['login_user'] . ' ';
		#echo 'First question is ' . $questions[0];
		#print_r($_POST);
		$username=mysqli_real_escape_string($db,$_SESSION['login_user']);
		$questionNumber = mysqli_real_escape_string($db,$_POST['questionNumber']);
		$subjectID = mysqli_real_escape_string($db,$_POST['actualSubject']);
		$chapterID = mysqli_real_escape_string($db,$_POST['actualChapter']);
		$score = 0;
		$maxPoints = 0;

		for($i = 0; $i < $_POST['questionNumber']; $i++){
			$question = mysqli_real_escape_string($db,$questions[$i]); # iterates through the selected questions
			$index = $i+1;
			$studentAnswer = 'studentAnswer' . $index;
			$answer = mysqli_real_escape_string($db,$_POST[$studentAnswer]);
			$query = "SELECT * FROM questions WHERE questionID = '$question'";
			$result = mysqli_query($db,$query);
			$row = mysqli_fetch_assoc($result);
			if($row['questionType'] == "TF"){
				$correctAnswer = $row['answerTrueFalse'];
			}else{
				$correctAnswer = $row['answerABCD'];
			}

			$results_info_sql_query = "INSERT INTO `results_info` (`questionID`, `subjectID`, `chapterID`, `studentUser`, `studentAnswer`, `correctAnswer`) VALUES ('$question', '$subjectID', '$chapterID', '$username', '$answer', '$correctAnswer')";
			$results_info_result = mysqli_query($db,$results_info_sql_query);
			if($answer == $correctAnswer){
				$score = $score+$row['correctPoints'];
			}else{
				$score = $score-$row['assHolePoints'];
			}
			$maxPoints = $maxPoints + $row['correctPoints'];
		}

		if($score < 0){ # can't have negative score
			$score = 0;
		}

		$results_sql_query = "INSERT INTO `results` (`subjectID`, `chapterID`, `studentUser`, `score`, `maxPoints`) VALUES ('$subjectID', '$chapterID', '$username', '$score', '$maxPoints')";
		$results_result = mysqli_query($db,$results_sql_query);
	}
?>

<html>
	<head>
		<title>Ended exam</title>
		<link rel="stylesheet" type="text/css" href="studentStyle.css">
	</head>
	<body>
	<?php
			include($root . "/student/header.php")
	?>
	<h1>Your exam has ended!</h1>
	<li><a href="/student/student.php">Go to main menu</a></li>

	<?php
			include($root . "/student/footer.php")
	?>

	</body>
</html>